<template>
  <div class="box">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="flex-start"
          >
            <el-form-item
              v-if="userType == '00'"
              label="所属网点"
              prop="networkLevel"
            >
              <el-select
                v-model="form.networkLevel"
                placeholder="请选择所属网点"
                style="width: 275px"
                @change="bg"
              >
                <el-option
                  v-for="item in networkList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="结算时间" prop="time">
              <el-date-picker
                v-model="form.time"
                style="width: 650px"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="mxDateChange"
              />
            </el-form-item>
            <el-form-item label="结算状态" prop="settleStatus">
              <el-select
                v-model="form.settleStatus"
                placeholder="请选择结算状态"
                style="width: 275px"
              >
                <el-option label="全部" value="1" />
                <el-option label="结算中" value="2" />
                <el-option label="已完成" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="mxClear">重置</el-button>
              <el-button plain icon="el-icon-upload2" @click="exportData"
                >导出</el-button
              >
              <el-button plain icon="el-icon-setting" @click="openSetting"
                >出港返利毛利配置参数</el-button
              >
              <el-button plain icon="el-icon-setting" @click="openkhSetting(0)"
                >客户配置参数</el-button
              >
              <el-button plain icon="el-icon-setting" @click="openkhSetting(1)"
                >子客户配置参数</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <div style="display: flex; justify-content: flex-end; margin-bottom: 30px">
      <el-button
        type="primary"
        style="margin-right: 20px"
        @click="downloadExcel"
        >下载Excel模板</el-button
      >
      <input
        ref="fileInput"
        style="display: none"
        type="file"
        @change="uploadExcel"
      />
      <el-button type="primary" @click="uploading">点击上传</el-button>
    </div>
    <el-row>
      <el-col :span="24">
        <div v-if="!isObjectEmpty(tableData)">
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData.list.data"
            tooltip-effect="dark"
            style="width: 100%"
            border
            row-key="id"
            lazy
            :load="load"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            max-height="600"
          >
            <el-table-column
              v-for="(t, n) in tableData.fields"
              :key="n"
              :prop="t.fields"
              :label="t.translate"
              :fixed="n < 2"
              :min-width="
                flexColumnWidth(t.translate, t.fields, tableData.list.data)
              "
              align="center"
            >
              <template slot-scope="scope">
                <a
                  v-if="t.isPoint != null"
                  style="color: skyblue"
                  @click="searchDetail(scope.row, t)"
                  >{{ scope.row[t.fields] }}</a
                >
                <span v-else>{{ scope.row[t.fields] }}</span>
              </template>
              <el-table-column
                v-for="(s, i) in t.sunList"
                v-show="s.sunList != null"
                :key="i"
                :prop="s.fields"
                :label="s.translate"
                :min-width="
                  flexColumnWidth(s.translate, s.fields, tableData.list.data)
                "
                align="center"
              >
                <template slot-scope="scope">
                  <a
                    v-if="s.isPoint != null"
                    style="color: skyblue"
                    @click="searchDetail(scope.row, s)"
                    >{{ scope.row[s.fields] }}</a
                  >
                  <span v-else>{{ scope.row[s.fields] }}</span>
                </template>
                <el-table-column
                  v-for="(a, b) in s.sunList"
                  v-show="a.sunList != null"
                  :key="b"
                  :prop="a.fields"
                  :label="a.translate"
                  :min-width="
                    flexColumnWidth(a.translate, a.fields, tableData.list.data)
                  "
                  align="center"
                >
                  <template slot-scope="scope">
                    <a
                      v-if="a.isPoint != null"
                      style="color: skyblue"
                      @click="searchDetail(scope.row, a)"
                      >{{ scope.row[a.fields] }}</a
                    >
                    <span v-else>{{ scope.row[a.fields] }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="isObjectEmpty(tableData)">
          <empty />
        </div>
      </el-col>
    </el-row>
    <div class="block" style="display: flex; justify-content: flex-end">
      <el-pagination
        :current-page="form.pageDate.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="form.pageDate.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="出港返利毛利配置参数"
      :visible.sync="dialogFormVisible"
      width="30%"
      @open="getSelectDisposition"
    >
      <div style="height: 400px; overflow-y: auto">
        <el-form :model="updateData">
          <el-form-item
            v-for="(i, n) in updateData.fields"
            :key="n"
            :label="i.translate"
            :label-width="formLabelWidth"
          >
            <el-input v-model="updateData.list[i.fields]" style="width: 50%" />
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="uodateParams">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="configTitle"
      :visible.sync="khdialogFormVisible"
      width="30%"
      @open="khgetSelectDisposition"
      @close="close"
    >
      <div style="height: 400px; overflow-y: auto">
        <el-form :model="khupdateData">
          <el-form-item label="客户名称" :label-width="formLabelWidth">
            <el-select
              v-if="activeType === 0"
              v-model="khupdateData.list.id"
              placeholder="请选择"
              @change="getprice"
            >
              <el-option
                v-for="item in khlist"
                :key="item.value"
                :label="item.clientName"
                :value="item.id"
              />
            </el-select>
            <el-select
              v-if="activeType === 1"
              v-model="khupdateData.list.id"
              placeholder="请选择"
              filterable
              @change="getprice"
            >
              <el-option
                v-for="item in childKhList"
                :key="item.value"
                :label="item.clientName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-for="(i, n) in khupdateData.fields"
            :key="n"
            :label="i.translate"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="khupdateData.list[i.fields]"
              style="width: 50%"
            />
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="uodatekhParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOutletsList,
  getSubjectFirstList,
  // getSubjectList,
  // subjectSearch,
  // addSubject,
} from "@/api/dashboard";
import { exportDataCGFLML, drdata, Dwtemplate } from "@/api/home";
import empty from "@/components/menuComponent/empty.vue";

// import { CostSmallKindApi, CostBigKindApi } from '@/api/HqFinancePanel'
import {
  OutboundGrossProfitinit,
  outReturnSheetSelectAll,
  outReturnSheetUpdate,
  getkhlist,
  getChildKhList,
  getcgflmlkhparams,
  comfigupdatekhparams,
  getChildTableData,
} from "@/api/apifile/Networkfinance";
export default {
  components: { empty },
  data() {
    return {
      userType: localStorage.getItem("userType") || null,
      childKhList: [],
      activeType: null,
      khlist: [],
      loading: false,
      isart: false,
      form: {
        time: "",
        networkLevel: 0,
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      updateData: {},
      khupdateData: {
        list: {},
      },

      formLabelWidth: "220px",
      addForm: {
        networkNameId: "",
        firstId: "",
        secondName: "",
      },
      // 一级网点
      SubjectFirstList: [],
      // 网点列表
      networkList: [
        { value: 0, label: "网点" },
        { value: 1, label: "承包区" },
        { value: 2, label: "客户" },
      ],
      pages: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogFormVisible: false,
      khdialogFormVisible: false,

      currentPage4: 4,
      tableData: {},
      rules: {
        networkLevel: [
          { required: true, message: "请选择网点名称", trigger: "blur" },
        ],
        time: [{ required: true, message: "请选择日期", trigger: "blur" }],
      },
      CostSmallKindlist: [], // 小类
      CostBigKindlist: [], // 大类
      uploadedData: null,
      searchForm: {
        contractArea: "",
        endTime: "",
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
        settleNetworkNameId: "",
        startTime: "",
        type: 0,
      },
      configTitle: "客户配置参数",
    };
  },
  created() {
    // CostSmallKindApi().then((res) => {
    //   // console.log('小类', res)
    //   this.CostSmallKindlist = res.data
    // })
    // CostBigKindApi().then((res) => {
    //   // console.log('大类', res)
    //   this.CostBigKindlist = res.data
    // })
    // // -----------------------
    // // this.getList();
    // // this.getOutLet();
    // // this.getSubjectFirst();
    this.khmclist();
  },
  methods: {
    load(tree, treeNode, resolve) {
      getChildTableData({
        id: tree.id,
        name: tree.name,
        date: tree.date,
        networkLevel: tree.networkLevel,
      })
        .then((res) => {
          const data = res.data;
          resolve(data);
        })
        .catch((err) => {
          // console.log(err);
          resolve([]);
        });
    },
    close() {
      this.khdialogFormVisible = false;
      this.khupdateData = {
        list: {},
      };
    },
    async getprice(value) {
      const res = await getcgflmlkhparams(value);
      this.khupdateData = res.data;
    },
    // 获取客户名称列表
    async khmclist() {
      const res = await getkhlist();
      this.khlist = res.data;
      const list = await getChildKhList();
      this.childKhList = list.data;
    },
    searchDetail(item, type) {
      // console.log(item);
      this.searchForm.contractArea = this.networkList.filter(
        (el) => el.value === this.form.networkLevel
      )[0].label;
      this.searchForm.settleNetworkNameId = item.name;
      this.searchForm.type = type.isPoint;
      this.$store.state.app.cgfmltab = this.searchForm;
      this.$router.push({
        path: "OutboundGrossProfitDetail",
      });
    },
    uploading() {
      if (this.$refs.fileInput.value === "") {
        this.$refs.fileInput.click();
      } else {
        this.$message.info("上一个文件还没上传完请稍后");
      }
    },
    async uploadExcel(e) {
      // console.log(e);
      this.$notify.info({
        title: "开始导入...",
      });
      const file = e.target.files[0];
      const formData = new FormData();
      formData.append("file", file); // 假设后端接口接收的字段名为 'file'
      const res = await drdata(formData);
      // console.log(res);
      if (res.size === 60) {
        this.$notify({
          title: "导入失败",
          type: "error",
        });
      } else {
        this.$notify({
          title: "导入成功",
          type: "success",
        });
      }
      this.$refs.fileInput.value = "";
    },
    // 下载xlsx表格
    downloadExcel() {
      Dwtemplate().then((res) => {
        const url = window.URL.createObjectURL(new Blob([res]), {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "剔除票数模板.xlsx"); // 设置下载的文件名
        document.body.appendChild(link);
        link.click();
        link.parentNode.removeChild(link);
        this.$notify({
          title: "下载成功",
          type: "success",
        });
      });
    },
    exportData() {
      this.$refs.form.validate((res) => {
        if (res) {
          // this.$notify.info({
          //   title: '开始准备下载...'
          // })
          exportDataCGFLML(this.form).then((res) => {
            // const url = window.URL.createObjectURL(new Blob([res]), { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
            // const link = document.createElement('a')
            // link.href = url
            // link.setAttribute('download', '出港返利毛利报表.xlsx') // 设置下载的文件名
            // document.body.appendChild(link)
            // link.click()
            // link.parentNode.removeChild(link)
            this.$notify({
              title: "请前往总部下载中心查看",
              type: "success",
            });
          });
        }
      });
    },
    isObjectEmpty(obj) {
      return Object.keys(obj).length === 0;
    },
    bg(value) {
      // // console.log(value)
      if (value === 2) {
        this.isart = true;
      } else {
        this.isart = false;
      }
    },

    search() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.init();
        }
      });
      // this.init()
    },
    init() {
      this.loading = true;
      OutboundGrossProfitinit(this.form).then((res) => {
        this.tableData = res.data;
        this.total = res.data.list.total;
        this.form.pageDate.pageNum = res.data.list.current;
        this.loading = false;
        this.$message.success("查询成功");
        this.loading = false;
        this.pages.pageNum = res.data.current;
      });
    },
    mxClear() {
      this.$refs.form.resetFields();
      this.form.startTime = "";
      this.form.endTime = "";
    },
    // ----------------------------
    mxDateChange(value) {
      // // console.log('日期', value)
      if (value != null) {
        this.form.startTime = value[0];
        this.form.endTime = value[1];
        this.searchForm.startTime = value[0];
        this.searchForm.endTime = value[1];
      }
    },
    handleCurrentChange(val) {
      this.form.pageDate.pageNum = val;
      this.init();
    },
    handleSizeChange(val) {
      this.form.pageDate.pageSize = val;
      this.init();
    },
    // -------------------------
    // 获取网点列表
    getOutLet() {
      getOutletsList().then((res) => {
        if (res.code === 200) {
          this.networkList = res.data;
        }
      });
    },
    // 获取一级网点下拉框
    getSubjectFirst() {
      getSubjectFirstList().then((res) => {
        if (res.code === 200) {
          this.SubjectFirstList = res.data;
        }
      });
    },
    // 显示表格数据
    // getList() {
    //   getSubjectList().then((res) => {
    //     if (res.code === 200) {
    //       this.tableData = res.data.data;
    //       this.total = res.data.total;
    //       this.pages = res.data.pages;
    //     } else {
    //       this.$message({
    //         message: res.msg,
    //         type: "warning",
    //       });
    //     }
    //   });
    // },
    // 打开弹窗
    onSubmit() {
      this.dialogFormVisible = true;
    },
    // 重置
    clear() {
      this.form = {};
      this.getList();
    },
    // 打开配置弹窗
    openSetting() {
      this.dialogFormVisible = true;
    },
    // 打开客户配置弹窗
    openkhSetting(type) {
      this.activeType = type;
      this.khdialogFormVisible = true;
      this.configTitle = type == 0 ? "客户配置参数" : "子客户配置参数";
    },
    // 获取出港返利毛利报表配置
    getSelectDisposition() {
      outReturnSheetSelectAll().then((res) => {
        if (res.code === 200) {
          this.updateData = res.data;
          // console.log("res", res);
        }
      });
    },
    // 获取客户配置
    khgetSelectDisposition() {
      // outReturnSheetSelectAll().then((res) => {
      //   if (res.code === 200) {
      //     this.khupdateData = res.data
      //     // console.log('reskh', res)
      //   }
      // })
    },
    // 修改出港返利毛利报表配置
    uodateParams() {
      outReturnSheetUpdate(this.updateData.list).then((res) => {
        if (res.code === 200) {
          this.dialogFormVisible = false;
          this.$message("修改成功，正在更新数据");
          this.init();
        }
      });
    },
    // 修改出港返利毛利客户配置
    uodatekhParams() {
      delete this.khupdateData.list.clientName;
      comfigupdatekhparams(this.khupdateData.list).then((res) => {
        if (res.code === 200) {
          this.khdialogFormVisible = false;
          this.$message("修改成功");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.flex-start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.flex-bettom {
  display: flex;
  justify-content: space-between;
}

.header {
  padding-bottom: 20px;
  border-bottom: 1px solid #ccc;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
